package ch.zbw.sysventory.agent.scanner;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.sysventory.agent.jWMI;
import ch.zbw.sysventory.agent.utils.PCTypeHelper;

public class WMIHelper {

	Logger logger = Logger.getRootLogger();

	public String getComputerName() {
		try {
			return this.getWMIValue("select * from Win32_ComputerSystem", "Name");
		} catch (Exception e) {
			logger.error("Cannot read computer name: " + e.getMessage(), e);
		}
		return "";
	}

	public String getIpAddress() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostAddress();
		} catch (UnknownHostException e) {
			logger.error("Cannot read ip address: " + e.getMessage(), e);
		}
		return "";
	}

	public String getOperatingSystem() {
		try {
			return System.getProperty("os.name") + " " + this.getWMIValue("select * from Win32_OperatingSystem", "CSDVersion") + " "
					+ this.getWMIValue("select * from Win32_ComputerSystem", "Systemtype");
		} catch (Exception e) {
			logger.error("Cannot read OS: " + e.getMessage(), e);
		}
		return "";
	}

	public String getCPU() {
		try {
			return this.getWMIValue("select Name from Win32_Processor", "Name");
		} catch (Exception e) {
			logger.error("Cannot read CPU: " + e.getMessage(), e);
		}
		return "";
	}

	public String getSID() {
		try {
			String sid = this.getWMIValue("SELECT * from Win32_UserAccount WHERE Name='Administrator' AND LocalAccount=True", "SID");
			if (sid.length() > 0 && sid.indexOf("-") > 0)
				return sid.substring(0, sid.lastIndexOf("-"));
		} catch (Exception e) {
			logger.error("Cannot read SID: " + e.getMessage(), e);
		}
		return "";
	}

	public String getRAM() {
		try {
			ActiveXComponent axWMI = new ActiveXComponent(String.format("winmgmts:\\\\%s\\root\\CIMV2", "localhost"));
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant("select * from Win32_OperatingSystem"));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				String physicalRam = Dispatch.call(item, "TotalVisibleMemorySize").toString();
				return physicalRam;
			}
		} catch (Exception e) {
			logger.error("Cannot read ram: " + e.getMessage(), e);
		}
		return "";
	}

	public String getComputerType() {
		try {
			ActiveXComponent axWMI = new ActiveXComponent(String.format("winmgmts:\\\\%s\\root\\CIMV2", "localhost"));
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant("SELECT * FROM Win32_ComputerSystem"));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				int pcType = Dispatch.call(item, "PCSystemType").getInt();
				return PCTypeHelper.getPCTypeAsString(pcType);
			}
		} catch (Exception e) {
			logger.error("Cannot read computer type: " + e.getMessage(), e);
		}
		return PCTypeHelper.getPCTypeAsString(0);
	}

	public String getMACAddress() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
			byte[] mac = iface.getHardwareAddress();
			StringBuilder sb = new StringBuilder(18);
			for (byte b : mac) {
				if (sb.length() > 0)
					sb.append(':');
				sb.append(String.format("%02x", b));
			}
			return sb.toString();
		} catch (Exception e) {
			logger.error("Cannot read MAC address: " + e.getMessage(), e);
		}
		return "";
	}

	private String getWMIValue(String query, String attributes) {
		String value = "";
		try {
			value = jWMI.getWMIValue(query, attributes);
		} catch (Exception e) {
			logger.error("Cannot read wmi value (" + query + "): " + e.getMessage(), e);
		}
		return value;
	}

}
